import React, { useContext, useState, useEffect, useRef } from 'react';
import { getMessage, TextWidget } from '@inbiz/react';
import MultilingualInput from '../../MultilingualInput/index';
import { EditableContext } from './Content';
import { Input, Form } from 'antd';

interface Item {
  id: string;
  value: string;
  name: string;
}

interface EditableRowProps {
  index: number;
}

// 可修改表格组件-行
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  return <tr {...props} />;
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  nowKey: string;
  setNowKey: (b: string) => void;
  handleSave: (record: Item) => void;
}

// 可修改表格组件-列（单元格）
const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  nowKey,
  setNowKey,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing && inputRef.current) {
      let dom: HTMLElement = inputRef.current;
      dom?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    if (record.id.endsWith('_nz')) {
      return;
    }
    setNowKey(record.id);
    setEditing(true);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      handleSave({ ...record, ...values });
    } catch (err) {}
    setEditing(false);
  };

  let childNode = children;

  if (editable) {
    const placeMessage = getMessage(
      'PermissionConfig.placeholder_please_input',
    ); //请输入
    childNode =
      editing && nowKey === record.id ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title}${getMessage(
                'PermissionConfig.message_should_not_null',
              )}`, // 不能为空
            },
          ]}
        >
          {dataIndex === 'name' ? (
            <MultilingualInput
              ref={inputRef}
              onPressEnter={save}
              onBlur={save}
              placeholder={placeMessage}
            />
          ) : (
            <Input
              ref={inputRef}
              onPressEnter={save}
              onBlur={save}
              placeholder={placeMessage}
            />
          )}
        </Form.Item>
      ) : (
        <div
          className={
            record.id.endsWith('_nz')
              ? `editable-cell-value-wrap editable-cell-value-wrap-disabled`
              : 'editable-cell-value-wrap'
          }
          id={`cell-${dataIndex}-${record.id}`}
          style={{ paddingRight: 24 }}
          onClick={toggleEdit}
        >
          {dataIndex === 'name' ? (
            <TextWidget>{children?.[1] || children}</TextWidget>
          ) : (
            children
          )}
        </div>
      );
  }

  return <td {...restProps}>{childNode}</td>;
};

export { EditableRow, EditableCell };
